package controller

import (
	"strconv"
	"strings"

	"github.com/bear/wolf/model"
	"github.com/bear/wolf/request"
	"github.com/bear/wolf/utils"
	"github.com/gin-gonic/gin"
)

func CreateProject(c *gin.Context){
	var req request.ProjectReq
		
	if err := c.ShouldBindJSON(&req);err !=nil{
		utils.Failed(c,"无效的请求:" + err.Error())
		return
	}
	// 使用工具函数解析日期
	beginAt1, _ := utils.ParseDate(req.BeginAt)
	endAt1 , _ := utils.ParseDate(req.EndAt)

	existuser, _ := model.GetProejctName(req.ProjectName)
	if existuser !=nil{
		utils.Failed(c,"数据已存在")
		return
	}
	// 构建Project对象
	project := model.Project{
		ProjectName: req.ProjectName,
		BeginAt:     beginAt1,
		EndAt:       endAt1,
	}

	if err := model.CreateProject(&project);err!=nil{
		utils.Failed(c,"创建项目失败" + err.Error())
		return
	 }
	utils.Success(c,gin.H{
		"projectName": req.ProjectName,
	})
}

func DeleteProjectByid(c *gin.Context){
	id := c.Query("id")
	if strings.TrimSpace(id) == ""{
		utils.Failed(c,"id不能为空:")
	}	
	int_id, _ := strconv.Atoi(id)
	result := model.DeleteProjectByid(int_id)
	if result !=nil{
		utils.Failed(c,"删除失败" + result.Error())
		return
	}
	utils.Success(c,gin.H{
		"id":       id,
	})
}	

func UpdateProject(c *gin.Context){
	var req request.ProjectuPReq 
	if err := c.ShouldBindJSON(&req); err !=nil{
		utils.Failed(c,"无效的请求:" + err.Error())
		return
	}
	count := model.GetIdExist(req.Id)
	if count == 0 {
		utils.Failed(c,"id数据不存在:")
		return
	}
	beginAt1, _ := utils.ParseDate(req.BeginAt)
	endAt1 , _ := utils.ParseDate(req.EndAt)

	// 构建Project对象
	project := model.Project{
		Id : req.Id,
		ProjectName: req.ProjectName,
		BeginAt:     beginAt1,
		EndAt:       endAt1,
	}

	result := model.UpdateByid(&project)
	if result !=nil{
		utils.Failed(c,"更新失败" + result.Error())
		return
	}
	utils.Success(c,gin.H{
		"id":       req.Id,
	})
}

func GetOnProject(c *gin.Context){
	id := c.Query("id")
	if strings.TrimSpace(id) == ""{
		utils.Failed(c,"id不能为空:")
		return
	}
	project := model.GetProjectById(id)
	if project.Id == 0 {
	utils.Failed(c,"暂无数据:")
		return
	}
	response := request.ProjectRespons{
		Id: project.Id,
		ProjectName: project.ProjectName,
		BeginAt: utils.FormatDate(project.BeginAt),
		EndAt: utils.FormatDate(project.EndAt),
	}
	utils.Success(c,response)
}

func GetListProject(c *gin.Context,){
	var req request.ProjectReq 
	if err := c.ShouldBindJSON(&req); err !=nil{
		utils.Failed(c,"无效的请求:" + err.Error())
		return
	}

	projectList :=model.GetProjectList(req)
		// 转换时间格式
	var respList [] request.ProjectRespons

	for _, project := range projectList {
		respList = append(respList, request.ProjectRespons{
			Id:          project.Id,
			ProjectName: project.ProjectName,
			BeginAt:     utils.FormatDateTime(project.BeginAt),
			EndAt:       utils.FormatDateTime(project.EndAt),
			CreateAt:    utils.FormatDateTime(project.CreateAt),
			UpdateAt:    utils.FormatDateTime(project.UpdateAt),
		})
	}

	utils.Success(c,respList)
}